using System.Collections.Generic;
using UnityEngine;

namespace IQIGame.Onigao.GamePlay
{
    /// <summary>
    /// 为UIN_BaseMapSymbol定制的对象池
    /// </summary>
    public partial class UIMapManager
    {
        private abstract class BaseMapSymbolPool
        {
            private GameObject prefab { get; }
            private Stack<UIBaseMapSymbol> poolItems { get; }

            protected BaseMapSymbolPool(GameObject prefab)
            {
                this.prefab = prefab;
                this.prefab.SetActive(false);
                poolItems = new Stack<UIBaseMapSymbol>();
            }

            public void PutOne(UIBaseMapSymbol symbol)
            {
                symbol.Hide();
                symbol.Reset();
                symbol.gameObject.transform.SetParent(Instance.root.transform);
                poolItems.Push(symbol);
            }

            public abstract UIBaseMapSymbol GetOne();

            protected UIBaseMapSymbol GetOne<T>() where T : UIBaseMapSymbol, new()
            {
                if (poolItems.Count > 0)
                {
                    var item = poolItems.Pop();
                    item.transform.SetAsLastSibling();
                    return item;
                }

                var go = Object.Instantiate(prefab);
                var newItem = new T();
                newItem.Init(go);
                return newItem;
            }

            public void Clear()
            {
                while (poolItems.Count > 0)
                {
                    poolItems.Pop().Dispose();
                }
            }
        }

        private class MapSymbolPool<T> : BaseMapSymbolPool where T : UIBaseMapSymbol, new()
        {
            public MapSymbolPool(GameObject prefab) : base(prefab)
            {
            }

            public override UIBaseMapSymbol GetOne()
            {
                return GetOne<T>();
            }
        }
    }
}